import {
	resultHos,
	resultDept,
	resultDocto,
	indexhosp,
	searchNav
} from '@/api/home/search.js'
import homeApii from '@/api/homee'
const state = {
	keyWord: {
		value: '',
		precise: false,
		type: 0, //0：未知 1:医院 2:科室 3:专家 4:疾病
	}, //搜索词
	topSearchButton: 1, //选中状态的id，1医院 2科室 3医生
	navCity: {
		id: '',
		name: '全部'
	}, //首页选中的城市,nav用
	IndexCityNav: {
		id: '',
		name: '全部'
	}, //搜索选中的城市,nav用
	zone: {
		id: '',
		name: ''
	}, //选中区域
	navActiveTitle: '', //当前nav，用于路由后丢失active
	// isNavCity:false,
	token: '',
	PopUpSarCh: '', //联想词的v-model
	selectGroup: [], //智能排序
	selectGroupResult: [], //智能排序选项，用来接接口传参
	aiSortGroup: [], //筛选
	aiSortGroupResult: [], //筛选，用来接接口传参
	brand: [{
		title: '医院',
		number: 100,
		id: 1
	}, {
		title: '科室',
		number: 20,
		id: 2
	}, {
		title: '医生',
		number: 999,
		id: 3
	}],
	hospDetailsInfo: '', //医院详情富文本
	currentHosp: {}, //选择当前分院列表，切换分院页面
	addList: [], //分院地址列表
	DepItemList: [], //热门科室和其他科室列表（科室详情页面）
	book_rules: '', //预约规则
	treat_navigation: '', //院内指南
	busAddress: '', //公交地址
	depNotice: '', //科室公告
	depDetailsInfo: '',
	searchTopData: [], //包含了按钮和排班日期，搜索详情页面
	geoList: {}, //获取地理信息
	serviceDate: '', //当前选中的日期，空就是全部
	hosList: [], //医院搜索关键词列表
	deptList: [], //科室列表
	indexhosList: {
		total: 0,
		list: []
	}, //首页列表
	depList: [], //科室搜索关键词列表
	doctorList: [], //医生搜索关键词列表
	pageStatus: 'loadmore', //翻页，加载前值为loadmore，加载中为loading，没有数据为nomore
	currentPage: 1, //当前页
	totalCount: 0, //总条数
	totalPage: 0, //总页数
	hasHao: false, //列表有号无号使用
	navIndexData: {
		navActiveTitle: '', //当前nav，用于路由后丢失active
		selectGroup: [], //智能排序
		selectGroupResult: [], //智能排序选项，用来接接口传参
		aiSortGroup: [], //筛选
		aiSortGroupResult: [], //筛选，用来接接口传参
	},
	pageStatusIndex: 'loadmore', //首页翻页，加载前值为loadmore，加载中为loading，没有数据为nomore
	currentPageIndex: 1, //首页当前页
	totalCountIndex: 0, //首页总条数
	totalPageIndex: 0, //首页总页数
	frozen: false, //这里是传来
	hasHaoFlag: 1, //有号无号分页判断用哪个接口,搜索结果页用,区分下拉刷新用
	resultToCity: false, //搜索结果页到选择城市页面,区分使用有号还是无号请求接口
	IndexpopupShow: false, //首页固定
	popupShow: false, //详情页固定
	topHight: 0, //监听首页滚动距离
	ResultTopHight: 0, //结果页监听距离
	hosFrozen: false
};
//筛选只有一个数组，aiSortGroupResult[0].id
// aiSortGroupResult[{
// 	0: id: "d_ai_2"
// 	isChecked: true
// 	name: "aiSort"
// 	sort: 3
// 	text: "级别优先"
// }]

//selectGroupResult: [
//     {
//         "text": "医院等级",
//         "list": "h_level_0,h_level_1,h_level_2,h_level_3"
//     },
//     {
//         "text": "医院类型",
//         "list": "h_type_1,h_type_2"
//     },
//     {
//         "text": "医院性质",
//         "list": "h_nature_0,h_nature_1"
//     },
//     {
//         "text": "医院服务",
//         "list": "h_service_0,h_service_1"
//     }
// ]

const mutations = {
	GETDOCLIST(state, res) {
		state.hotDoc = res
	},
	GETKESHILIST(state, res) {
		//console.log(res,'00000')
		state.hotDep = res
	},
	async NAVHOS(state, obj) {
		state.frozen = false
		let {
			params,
			flag
		} = obj
		if (state.topSearchButton == 1) { //医院
			let data = state.selectGroupResult
			data.map(v => {
				if (v.text == '医院等级' && v.list !== '') { //医院级别
					params.hosLevel = v.list
				}
				if (v.text == '医院类型' && v.list !== '') { //医院级别
					params.hosType = v.list
				}
				if (v.text == '医院性质' && v.list !== '') { //医院级别
					params.hosNature = v.list
				}
				if (v.text == '医院服务' && v.list !== '') { //医院级别
					params.hosService = v.list
				}
			})
			if (flag == 'roll') {
				//console.log(state.currentPage,'sdfsdf');
				if (state.totalCount > 0 && state.currentPage < state.totalPage) {
					state.currentPage = ++state.currentPage
					params.pageNum = state.currentPage
					//state.pageStatus = 'loadmore'
					let ress = await resultHos(params)
					state.totalPage = Math.ceil(ress.data.total / 5)
					//console.log(ress,'ress','ADDHIS');
					state.totalCount = ress.data.total
					state.hosList.list.push(...ress.data.list)
					//console.log(ress,'ress', state.currentPage,state.totalPage);
					uni.hideLoading()
					state.frozen = true
					return
				} else {
					//console.log(12333);
					state.pageStatus = 'nomore'
					uni.hideLoading()
					return
				}
			}
			state.hosList = []
			state.currentPage = 1
			state.pageStatus = 'loadmore'
			let res = await resultHos(params)
			uni.hideLoading()
			state.frozen = true
			state.searchTopData.map((v) => {
				if (v.type == 'hos') {
					v.total = res.data.total
				}
				return v
			})
			await this.commit('CHANGETITLENUMBER')
			//console.log(state.searchTopData,'sdfsdf');
			if (res.data.total < 5) {
				state.pageStatus = 'nomore'
			}
			state.totalCount = res.data.total
			state.totalPage = Math.ceil(res.data.total / 5)
			state.hosList = res.data
			//console.log(state.hosList);
		}
	},
	async NAVDOCTOR(state, obj) {
		state.frozen = false
		let {
			params,
			flag
		} = obj
		if (state.topSearchButton == 3) { //医生
			let data = state.selectGroupResult
			data.map(v => {
				if (v.text == '医院等级' && v.list !== '') { //医院级别
					params.hosLevel = v.list
				}
				if (v.text == '医生职称' && v.list !== '') { //医院级别
					params.jobTitle = v.list
				}
			})

			if (flag == 'roll') {
				//console.log(state.currentPage,'sdfsdf');
				if (state.totalCount > 0 && state.currentPage < state.totalPage) {
					state.currentPage = ++state.currentPage
					params.pageNum = state.currentPage
					//state.pageStatus = 'loadmore'
					let ress = await resultDocto(params)
					state.totalPage = Math.ceil(ress.data.total / 5)
					//console.log(ress,'ress','ADDHIS');
					state.totalCount = ress.data.total
					state.doctorList.list.push(...ress.data.list)
					//console.log(ress,'ress', state.currentPage,state.totalPage);
					uni.hideLoading()
					state.frozen = true
					return
				} else {
					//console.log(12333);
					state.pageStatus = 'nomore'
					uni.hideLoading()
					return
				}
			}
			state.doctorList = []
			state.currentPage = 1
			state.pageStatus = 'loadmore'
			let res = await resultDocto(params)
			uni.hideLoading()
			state.searchTopData.map((v) => {
				if (v.type == 'doctor') {
					v.total = res.data.total
				}
				return v
			})
			await this.commit('CHANGETITLENUMBER')
			//console.log(state.searchTopData,'sdfsdf');
			if (res.data.total < 5) {
				state.pageStatus = 'nomore'
			}
			state.totalCount = res.data.total
			state.totalPage = Math.ceil(res.data.total / 5)
			state.doctorList = res.data
			state.frozen = true
			//let res = await resultDocto(params)
			//state.doctorList = res.data
			//console.log(res,'doctor');
		}


	},
	async NAVDEP(state, obj) {
		state.frozen = false
		let {
			params,
			flag
		} = obj
		if (state.topSearchButton == 2) { //科室
			let data = state.selectGroupResult
			data.map(v => {
				if (v.text == '医院等级' && v.list !== '') { //医院级别
					params.hosLevel = v.list
				}
				if (v.text == '科室类型' && v.list !== '') { //医院级别
					params.deptType = v.list
				}
			})
			if (flag == 'roll') {
				//console.log(state.currentPage,'sdfsdf');
				if (state.totalCount > 0 && state.currentPage < state.totalPage) {
					state.currentPage = ++state.currentPage
					params.pageNum = state.currentPage
					//state.pageStatus = 'loadmore'
					let ress = await resultDept(params)
					state.totalPage = Math.ceil(ress.data.total / 5)
					// console.log(ress,'ress','ADDHIS');
					state.totalCount = ress.data.total
					state.deptList.list.push(...ress.data.list)
					//console.log(ress,'ress', state.currentPage,state.totalPage);
					uni.hideLoading()
					state.frozen = true
					return
				} else {
					//console.log(12333);
					state.pageStatus = 'nomore'
					uni.hideLoading()
					return
				}
			}
			state.deptList = []
			state.currentPage = 1
			state.pageStatus = 'loadmore'
			let res = await resultDept(params)
			uni.hideLoading()
			state.depList = res.data
			state.searchTopData.map((v) => {
				if (v.type == 'dept') {
					v.total = res.data.navTotal //顶部按钮赋值，这里用了navtaotal这个字段，有别于医院医生用的total
				}
				return v
			})
			await this.commit('CHANGETITLENUMBER')
			if (res.data.total < 5) {
				state.pageStatus = 'nomore'
			}
			state.totalCount = res.data.total
			state.totalPage = Math.ceil(res.data.total / 5)
			state.deptList = res.data
			state.frozen = true
			//console.log(res,'dep');
		}
	},
	COMMENTPARAMS(state, obj) {
		let {
			params,
			flag
		} = obj
		params.keyWord = state.keyWord.value
		params.type = state.keyWord.type
		params.precise = state.keyWord.precise
		if (state.serviceDate) {
			params.serviceDate = state.serviceDate
		}
		if (state.navCity.id) {
			params.city = state.navCity.id
		}
		if (state.zone.id) {
			params.countyId = state.zone.id
		}
		if (state.geoList.latitude) {
			params.location =
				`${state.geoList.longitude},${state.geoList.latitude}`
		}
		if (state.aiSortGroupResult.length > 0) {
			//this.aiSortGroupResult
			params.aiSort = state.aiSortGroupResult[0].id //筛选条件参数
		}
		uni.showLoading({
			title: '加载中',
			mask: true
		});
		//console.log(params,123333777);
		this.commit('NAVHOS', {
			'flag': flag,
			'params': params
		}) //医院
		this.commit('NAVDEP', {
			'flag': flag,
			'params': params
		}) //科室
		this.commit('NAVDOCTOR', {
			'flag': flag,
			'params': params
		}) //医生
		//uni.hideLoading()
	},
	async ADDHIS(state, flag) { //搜索结果,非首页用
		state.hasHaoFlag = 1
		let params = {
			hasHao: false //默认有号无号都显示
		}
		this.commit('COMMENTPARAMS', {
			'flag': flag,
			'params': params
		})
	},
	async NODATA(state, flag) { //搜索结果,非首页用
		state.hasHaoFlag = 2
		let params = {
			hasHao: true //默认有号无号都显示
		}
		//console.log(params.hasHao);
		this.commit('COMMENTPARAMS', {
			'flag': flag,
			'params': params
		})
	},
	async INDEXHOSDATA(state, flag) { //搜索结果,首页页用，独立主页数据
		state.frozen = false
		let params = {}
		if (state.serviceDate) {
			params.serviceDate = state.serviceDate
		}
		if (state.IndexCityNav.id) {
			params.city = state.IndexCityNav.id
		}
		// if (state.zone.id) {
		// 	params.countyId = state.zone.id
		// }
		if (state.geoList.latitude) {
			params.location =
				`${state.geoList.longitude},${state.geoList.latitude}`
		}
		uni.showLoading({
			title: '加载中',
			mask: true
		});

		if (state.navIndexData.aiSortGroupResult.length > 0) {
			//this.aiSortGroupResult
			params.aiSort = state.navIndexData.aiSortGroupResult[0].id //筛选条件参数
		}
		//console.log(params,123333777);
		let data = state.navIndexData.selectGroupResult
		data.map(v => {
			if (v.text == '医院等级' && v.list !== '') { //医院级别
				params.hosLevel = v.list
			}
			if (v.text == '医院类型' && v.list !== '') { //医院级别
				params.hosType = v.list
			}
			if (v.text == '医院性质' && v.list !== '') { //医院级别
				params.hosNature = v.list
			}
			if (v.text == '医院服务' && v.list !== '') { //医院级别
				params.hosService = v.list
			}
		})
		if (flag == 'roll') {
			//console.log(state.totalCountIndex, state.currentPageIndex , state.totalPageIndex,555)
			if (state.totalCountIndex > 0 && state.currentPageIndex < state.totalPageIndex) {
				state.currentPage = ++state.currentPageIndex
				params.pageNum = state.currentPageIndex
				//state.pageStatus = 'loadmore'
				let ress = await indexhosp(params)
				state.totalPageIndex = Math.ceil(ress.data.total / 5)
				state.totalCountIndex = ress.data.total
				state.indexhosList.list.push(...ress.data.list)
				//console.log(state.indexhosList.list);
				//console.log(ress,'ress','INDEXHOSDATA',state.totalCount);
				uni.hideLoading()
				state.frozen = true
				return
			} else {
				state.pageStatusIndex = 'nomore'
				uni.hideLoading()
				return
			}
		}
		state.indexhosList = {
			total: 0,
			list: []
		}
		state.pageStatusIndex = 'loadmore'
		let res = await indexhosp(params)
		state.indexhosList = res.data
		state.totalCountIndex = res.data.total
		state.currentPageIndex = 1  //不翻页的时候，
		if (res.data.total < 5) {
			state.pageStatusIndex = 'nomore'
		}
		state.totalPageIndex = Math.ceil(res.data.total / 5)
		uni.hideLoading()
		state.frozen = true
	},
	GETTOKEN(state) {
		return new Promise((resolve, reject) => {
			uni.login({
				provider: 'weixin',
				success: (re) => {
					console.log(res)
					let code = re.code
					// this.getopenid()
					const authCode = re.authCode;
					homeApii.getopenid({
						code: code
					}).then(res => {
						console.log(res)
						console.log("vuex")
						if (res.code == 4000) {
							uni.setStorageSync("token", res.data.token)
							this.$store.state.doc.token = res.data.token
							// this.token = res.data.token

							resovle()
						}
					})
				},
			})
			// my.getAuthCode({
			// 	scopes: 'auth_base',
			// 	success: res => {
			// 		const authCode = res.authCode;
			// 		homeApii.getopenid({
			// 			code: authCode
			// 		}).then(res => {
			// 			//console.log(res,'storeToken')
			// 			if (res.code == 4000) {
			// 				uni.setStorageSync("token", res.data.token)
			// 				state.token = res.data.token
			// 			}
			// 			resolve(true)
			// 		})
			// 	},
			// 	fail: err => {
			// 		console.log('my.getAuthCode 调用失败storeToken', err)
			// 	}
			// });
		})
	},
	async NAVGETDATA(state) {
		let topDataLength = state.searchTopData.findIndex(v => {
			if (v.total > 0 && v.type == 'hos') {
				state.topSearchButton = 1
			}
			if (v.total > 0 && v.type == 'dept') {
				//return    //暂时封锁科室跳转页面，不然线上版本会跳到死页面
				state.topSearchButton = 2 //暂时注释掉，不让他选按钮
			}
			if (v.total > 0 && v.type == 'doctor') {
				state.topSearchButton = 3
			}
			return v.total > 0
		})

		if (topDataLength == -1) {
			uni.navigateTo({
				url: `/pages/sousuo/search_hosp/empty_result`
			});
			return
		}
		let paramsType = Number(topDataLength) + 1
		if (paramsType == 1) { //医院
			let res = await searchNav('hos')
			state.selectGroup = res.data.selectGroup
			state.aiSortGroup = res.data.aiSortGroup
		}
		if (paramsType == 2) { //科室
			let res = await searchNav('dept')
			state.selectGroup = res.data.selectGroup
			state.aiSortGroup = res.data.aiSortGroup
		}
		if (paramsType == 3) { //医生
			let res = await searchNav('doctor')
			state.selectGroup = res.data.selectGroup
			state.aiSortGroup = res.data.aiSortGroup
		}
		uni.navigateTo({
			url: `/pages/sousuo/search_hosp/index`
		});
	},
	CHANGETITLENUMBER(state) {
		//console.log(state.brand,222);
		state.brand.map((v) => {
			//console.log(v,111);
			if (v.title == '医院') {
				state.searchTopData.map(value => {
					if (value.type == 'hos') {
						//console.log(v.number, value.total,'map000');
						v.number = value.total
					}
				})
			}
			if (v.title == '科室') {
				state.searchTopData.map(value => {
					if (value.type == 'dept') {
						v.number = value.total
					}
				})
			}
			if (v.title == '医生') {
				state.searchTopData.map(value => {
					if (value.type == 'doctor') {
						v.number = value.total
					}
				})
			}
			return v
		})
		//console.log(this.brand,this.$store.state.doc.searchTopData,'00000');
	},

	ALLRESET(state, page) {
		if (state.selectGroup.length > 1) {
			state.selectGroup.map((v) => {
				return v.list.map((value) => {
					value.isChecked = false
					return value
				})
			})
		}
		if (state.aiSortGroup.length > 1) {
			state.aiSortGroup.map((v, k) => {
				if (k == 0) {
					//console.log(v,k);
					v.isChecked = true
				} else {
					v.isChecked = false
				}
				return v
			})
		}
		state.pageStatus = 'loadmore' //翻页，加载前值为loadmore，加载中为loading，没有数据为nomore
		state.currentPage = 1 //当前页
		state.totalCount = 0 //总条数
		state.totalPage = 0 //总页数
		state.hasHaoFlag = 1
		state.zone = {
			id: '',
			name: ''
		} //清空区
		// if (page == 'index') {
		// 	state.navCity = state.IndexCityNav
		// }
		state.navCity = {
			id: '',
			name: '全部'
		}
		state.selectGroupResult = [] //把记录的按钮id清空下
	},
};

const actions = {
	async doclist({
		commit
	}, data) {
		// let res = await getDoctorList(data)
		// commit('GETDOCLIST', res)
		//return '111'
	},
};

export default {
	state,
	mutations,
	actions
};